package com.tticar.invmanager.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tticar.invmanager.common.utils.MyResponseBody;
import com.tticar.invmanager.entity.vo.MyPage;
import com.tticar.invmanager.service.IMCateTmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.tticar.invmanager.entity.MCateTmp;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 存货分类表 前端控制器
 * </p>
 *
 * @author joeyYan
 * @since 2018-10-10
 */
@Controller
@RequestMapping("/mCateTmp")
public class MCateTmpController extends BaseController {

    @Autowired
    private IMCateTmpService mCateTmpService;

    /**
     * 修复category中isLeaf问题
     * @return
     */
    @GetMapping("leaf")
    @ResponseBody
    public MyResponseBody leaf() {
        Wrapper wrapper = new EntityWrapper();
        List<MCateTmp> list = this.mCateTmpService.selectList(wrapper);
        for(MCateTmp tmp : list) {
            wrapper = new EntityWrapper();
            wrapper.ne("status", -1);
            wrapper.eq("pid", tmp.getId());
            int count = this.mCateTmpService.selectCount(wrapper);
            if(count > 0) {
                tmp.setIsLeaf(0);
            } else {
                tmp.setIsLeaf(1);
            }
            this.mCateTmpService.updateById(tmp);
        }
        return MyResponseBody.success();
    }

    @PostMapping
    @ResponseBody
    public MyResponseBody post(MCateTmp mCateTmp) {
        mCateTmpService.insertOrUpdate(mCateTmp);
        return MyResponseBody.success();
    }

    @PostMapping("delete")
    @ResponseBody
    public MyResponseBody delete(@RequestParam("ids[]") List<Long> ids) {
        MyResponseBody responseBody = MyResponseBody.success();
        mCateTmpService.delete(ids);
        return responseBody;
    }

    @GetMapping("{id}")
    @ResponseBody
    public MyResponseBody get(@PathVariable("id") Long id) {
        MyResponseBody responseBody = MyResponseBody.success();
        responseBody.setData(mCateTmpService.selectById(id));
        return responseBody;
    }

    @GetMapping("edit")
    public String edit(MCateTmp mCateTmp, ModelMap modelMap) {
        modelMap.put("id", mCateTmp.getId());
        return "/mCateTmp/mCateTmp_edit";
    }

    @GetMapping("list")
    @ResponseBody
    public Page list(MCateTmp mCateTmp, MyPage<MCateTmp> page) {
        return mCateTmpService.selectPage(mCateTmp, page);
    }

    @GetMapping
    public String index() {
        return "/mCateTmp/mCateTmp";
    }

}
